/**  2015-06-11 wangmi 登陆*/
var CommonData = function (param) {
    this.loginCode = "";
    this.loginState = "";

    this.setLoginState = function () {
        if (param.indexOf("state=") != -1) {
            var arr = param.split("&");
            if (arr[0].indexOf("state=") != -1) {
                this.loginState = param.split("&")[0].split("=")[1];
            } else if (arr[1].indexOf("state=") != -1) {
                this.loginState = param.split("&")[1].split("=")[1];
            }
        }
    };

    this.setLoginCode = function () {
        if (param.indexOf("code=") != -1) {
            var arr = param.split("&");
            if (arr[0].indexOf("code=") != -1) {
                this.loginCode = param.split("&")[0].split("=")[1];
            } else if (arr[1].indexOf("code=") != -1) {
                this.loginCode = param.split("&")[1].split("=")[1];
            }
        }
    };
}

var Login = function () {
    function loginSubmit() {
        // 登录类型；
        var formType = $("#formType").val();

        // 数值对象；
        var nameObj, passwordObj;

        // 手机验证码登录；
        if (formType == 1) {
            nameObj = $("#phone");
            passwordObj = $("#phoneCode");
        } else {
            nameObj = $("#uname");
            passwordObj = $("#psw");
        }
        if (nameObj.isValid()) {
            if (passwordObj.isValid()) {
                var username = nameObj.val();
                //添加cookie
                addCookie("userName", username, 7, "/");

                var password = passwordObj.val();
                var code = $("#code").val();
                var isCodeVali = $("#isCodeVali").val();
                if (isCodeVali == 'yes' && !$("#code").isValid()) {
                    $("#code").trigger("validate");
                    $(".login-btn").val("登录")
                    return false;
                }

                $.ajax({
                    url: "/login.htm",
                    type: "post",
                    data: {"username": username, "password": password, "code": code, "loginType": formType},
                    dataType: "json",
                    success: function (msg) {
                        var data = eval(msg);
                        if (data.actionStatus == 'success') {
                            var url = $("#mybackurl").val();
                            if (jQuery.trim(url) == "") {
                                url = '/index.htm';
                            }
                            
                            //处理神策
                            try
                            {
                              if(data.data!=null){
                                var loginId= data.data.loginUID + "";
                                sensors.login(loginId);
								
								var userNameSensors = data.data.loginUName;
								var memberIdSensors = data.data.memberId + "";
								var memberNameSensors = data.data.companyName;
								sensors.setProfile({
								  userName: userNameSensors,
								  memberName: memberNameSensors,
								  memberId: memberIdSensors
								})
                              }
                            }
                            catch(err)
                            {
                               //出现问题不做处理
                            }
                            //页面跳转
                            window.location.href = url;
                        } else {
                            if (data.isWeakPassword !== undefined && data.isWeakPassword){
                                $(".login-btn").val("登录");
                                $("#phone").val(data.backMobile);
                                if (data.backMobile !== ""){
                                    //添加cookie
                                    addCookie("userName", data.backMobile, 7, "/");
                                }
                                changeForm($("#changeForm"), true, 1);
                            } else {
                                $("#msg_error").show();
                                $("#msg_error").html('<span class="error">' + data.actionMessage + '</span>');

                                $(".login-btn").val("登录")
                                //每次登录失败，错误数累计加1，当错误 数大于3次时，显示验证码区域，需要输入验证码登录
                                if (parseInt(data.failCount) > 2) {
                                    $("#codeImage").attr("src", '/Image?t=' + Math.random());
                                    $("#codeDiv").show();
                                    $("#isCodeVali").val("yes");
                                }
                                return;
                            }

                        }
                    }
                });
            } else {
                passwordObj.trigger("validate");
                $(".login-btn").val("登录")
            }
        } else {
            nameObj.trigger("validate");
            $(".login-btn").val("登录")
        }
    };

    function addCookie(name, value, days, path) {
        var name = escape(name);
        var value = escape(value);
        var expires = new Date();
        expires.setTime(expires.getTime() + days * 3600000 * 24);
        //path=/，表示cookie能在整个网站下使用，path=/temp，表示cookie只能在temp目录下使用
        path = path == "" ? "" : ";path=" + path;
        //GMT(Greenwich Mean Time)是格林尼治平时，现在的标准时间，协调世界时是UTC,参数days只能是数字型
        var _expires = (typeof days) == "string" ? "" : ";expires=" + expires.toUTCString();
        document.cookie = name + "=" + value + _expires + path;
    };

    this.btnClick = function () {
        $(".login-btn").click(function () {
            $(this).val("正在登录中...");
            loginSubmit();
        });
    }

    this.imgClick = function () {
        $("#codeImage").click(function () {
            $(this).attr("src", '/Image?t=' + Math.random());
        });
    };

    //验证input输入的内容
    this.loginvalidator = function () {
        $("#login").validator({
            rules: {
                // 自定义loginName规则，填写用户名、手机号
                username: function (element) {
                    return this.test(element, "mobile") === true ||
                        '您输入的手机号码格式有误';
                },
                password: function (element) {
                    return this.test(element, "password") === true
                    '密码格式不准确';
                },
                checkCode: function (element) {
                    var flag = true;
                    var message = "";
                    $.ajax
                    ({
                        url: "/code_check.htm",
                        type: "post",
                        async: false,
                        data: {"code": $("#code").val()},
                        dataType: "json",
                        success: function (msg) {
                            var data = eval(msg);
                            if (data.actionStatus != 'success') {
                                flag = false;
                                message = data.actionMessage;
                            }
                        }
                    });
                    return flag || message;
                }
            },
            fields: {
                uname: {
                    rule: "required;username",
                    target: "#msg_error,#msg-ok1"
                },
                psw: {
                    rule: "required;",
                    target: "#msg_error,#msg-ok2"
                },
                code: {
                    rule: "required;checkCode",
                    target: "#msg_error,#msg-ok3"
                }
            },
            msgWrapper: 'span',
            msgMaker: function (opt) {
                return '<span class="' + opt.type + '">' + opt.msg + '</span>';
            },
            invalidClass: 'text-error',
            display: function (element) {
                return $(element).siblings('label').text();
            }
        });
        //解决ie下input的placeholder文字显示的问题
        $('input[placeholder]').placeholder();
    };
};

var WeiboLogin = function (code, state) {
    this.weibo = function () {
        queryWeiboData(code, state);
    };

    //取用户信息
    function queryWeiboData(code, state) {
        var access_data = {code: code};
        $.ajax
        ({
            url: "/member/user_weibo_info.htm",
            type: "post",
            data: access_data, // code
            dataType: "json",
            async: false,
            success: function (msg) {
                var responseData = eval(msg);
                if (responseData.actionStatus == "success") {
                    var data = eval("(" + responseData.actionMessage + ")");

                    var loginData = {
                        "openId": data.id,
                        "nickName": data.screen_name,
                        "figureUrl": data.profile_image_url
                    };
                    var bindLoginData = {"openId": data.id, "state": state, "nickName": data.screen_name};
                    //执行登录
                    if (state == "weibo") {
                        weiboLogin(loginData);
                    } else if (state == "weibobind") {
                        weiboBindLogin(bindLoginData);
                    }
                }

                if ((responseData.actionStatus != "success") && (state == "weibo")) {
                    alert("微博登录失败！"); //在 login.htm 页面直接弹出
                }

                if ((responseData.actionStatus != "success") && (state == "weibobind")) {
                    window.location.href = "//member.banksteel.com/member/user_bind_set.htm?bind=weibo_fail"; //回到 绑定设置页面 弹出失败弹窗
                }

            }
        });
    };

    //已经从新浪取回数据 执行登陆逻辑
    function weiboLogin(resMsg) {
        $.ajax
        ({
            url: "/member/user_weibo_login.htm",
            type: "post",
            data: resMsg,
            dataType: "json",
            async: false,
            success: function (msg) {
                var res_msg = eval(msg);
                if (res_msg.actionStatus == "success") {
                    if (res_msg.actionMessage == "index") {
                        //处理神策
                        try
                        {
                          if(res_msg.data!=null){
                            var loginId= res_msg.data.loginUID+"";
                            sensors.login(loginId);
                          }
                        }
                        catch(err)
                        {
                           //出现问题不做处理
                        }
                        window.location.href = "/index.htm";
                    }

                    if (res_msg.actionMessage == "bind") {
                    
                        var figureUrl=resMsg.figureUrl;
                        if(figureUrl!=null){
                          figureUrl=figureUrl.replaceAll("&","%26");
                        }
                    
                        window.location.href = "/member/forward_bind.htm?type=4&openId=" + resMsg.openId + "&nickName=" + resMsg.nickName + "&figureUrl=" + figureUrl;
                    }
                } else {
                    window.location.href = "index.htm";
                }

            }
        });
    };

    //使用绑定登陆
    function weiboBindLogin(resMsg) {
        $.ajax({
            type: "post",
            async: false,
            url: "/member/bind_third.htm",
            dataType: "json",
            data: resMsg,
            success: function (result) {
                var data = eval(result);
                if (data.actionStatus == 'success') {
                    window.location.href = "//member.banksteel.com/member/user_bind_set.htm";
                } else {
                    window.location.href = "//member.banksteel.com/member/user_bind_set.htm?bind=weibo_fail";
                }
            }
        });
    }
};

var QQLogin = function (code) {
    //QQ登录
    this.qq = function () {
        qqLoginHandle(code);
    };

    function qqLoginHandle(code) {
        //1，获取qq用户信息
        $.ajax({
            type: "post",
            url: "/member/user_qq_info.htm",
            data: {"code": code},
            async: false,
            dataType: "json",
            success: function (result) {
                var res_msg = eval(result);
                if (res_msg.actionStatus == "success") {
                    var resData = eval("(" + res_msg.actionMessage + ")");
                    var postData = {
                        "openId": resData.openid,
                        "unionId": resData.unionId,
                        "nickName": resData.nickname,
                        "figureUrl": resData.figureurl_qq_1
                    }    //figureurl_qq_1指40*40头像
                    //2，登录本系统
                    $.ajax({
                        type: "post",
                        async: false,
                        url: "/member/user_qq_login.htm",
                        dataType: "json",
                        data: postData,
                        success: function (result) {
                            var data = eval(result);
                            if (data.actionStatus == 'success') {
                                if (data.actionMessage == "index") {
                                    //3.1，已绑定QQ用户登录跳转到index页面
                                    //处理神策
                                    try
                                    {
                                      if(data.data!=null){
                                        var loginId= data.data.loginUID+"";
                                        sensors.login(loginId);
                                      }
                                    }
                                    catch(err)
                                    {
                                       //出现问题不做处理
                                    }
                                    window.location.href = "index.htm";
                                } else if (data.actionMessage == "bind") {
                                    //3.2，未绑定QQ用户登录跳转到绑定页面，tpye=2 QQ绑定
                                    
                                    var figureUrl=postData.figureUrl;
                                    if(figureUrl!=null){
                                      figureUrl=figureUrl.replaceAll("&","%26");
                                    }
                                    
                                    window.location.href = "/member/forward_bind.htm?type=2&openId=" + postData.openId + "&unionId=" + postData.unionId + "&nickName=" + postData.nickName + "&figureUrl=" + figureUrl;
                                }
                            } else {
                                window.location.href = "index.htm";
                            }
                        }
                    });
                } else {
                    alert("QQ登录失败");
                }
            }
        });
    }
};

var QQBind = function (code, state) {
    //QQ绑定
    this.qqbind = function () {
        qqBindHandle(code, state);
    };

    function qqBindHandle(code, state) {
        //1，获取qq用户信息
        $.ajax({
            type: "post",
            url: "/member/user_qq_info.htm",
            data: {"code": code},
            async: false,
            dataType: "json",
            success: function (result) {
                var res_msg = eval(result);
                if (res_msg.actionStatus == "success") {
                    var resData = eval("(" + res_msg.actionMessage + ")");
                    var postData = {
                        "openId": resData.openid,
                        "unionId": resData.unionId,
                        "state": state,
                        "nickName": resData.nickname
                    }
                    //2，进行qq绑定
                    $.ajax({
                        type: "post",
                        async: false,
                        url: "/member/bind_third.htm",
                        dataType: "json",
                        data: postData,
                        success: function (result) {
                            var data = eval(result);
                            if (data.actionStatus == 'success') {
                                //3，绑定QQ成功跳转到绑定设置页面
                                window.location.href = "//member.banksteel.com/console/#/member/personal/security-setting?flag=1";
                            } else {
                                window.location.href = "//member.banksteel.com/console/#/member/personal/security-setting?flag=0&type=qq"; //回到 绑定设置页面 弹出失败弹窗
                            }
                        }
                    });
                } else {
                    window.location.href = "//member.banksteel.com/console/#/member/personal/security-setting?flag=0&type=qq"; //回到 绑定设置页面 弹出失败弹窗
                }
            }
        });
    }

};

var WeixinLogin = function (code) {
    this.weixin = function () {
        weixinLoginHandle(code);
    }

    function weixinLoginHandle(code) {
        //微信登录
        //1，获取微信用户信息
        $.ajax({
            type: "post",
            url: "/member/user_weixin_info.htm",
            data: {"code": code},
            async: false,
            dataType: "json",
            success: function (result) {
                var res_msg = eval(result);
                if (res_msg.actionStatus == "success") {
                    var resData = eval("(" + res_msg.actionMessage + ")");
                    var postData = {
                        "openId": resData.openid,
                        "nickName": resData.nickname,
                        "unionId": resData.unionId,
                        "headImgurl": resData.headimgurl
                    }
                    //2，登录本系统
                    $.ajax({
                        type: "post",
                        async: false,
                        url: "/member/user_weixin_login.htm",
                        dataType: "json",
                        data: postData,
                        success: function (result) {
                            var data = eval(result);
                            if (data.actionStatus == 'success') {
                                if (data.actionMessage == "index") {
                                    //3.1，已绑定微信用户登录跳转到index页面
                                    //处理神策
                                    try
                                    {
                                      if(data.data!=null){
                                        var loginId= data.data.loginUID+"";
                                        sensors.login(loginId);
                                      }
                                    }
                                    catch(err)
                                    {
                                       //出现问题不做处理
                                    }
                                    window.location.href = "index.htm";
                                } else if (data.actionMessage == "bind") {
                                    //3.2，未绑定微信用户登录跳转到绑定页面，tpye=3微信绑定
                                    var figureUrl=postData.headImgurl;
                                    if(figureUrl!=null){
                                      figureUrl=figureUrl.replaceAll("&","%26");
                                    } 
                                    window.location.href = "/member/forward_bind.htm?type=3&openId=" + postData.openId + "&nickName=" + postData.nickName + "&unionId=" + postData.unionId + "&figureUrl=" + postData.headImgurl;
                                }
                            } else {
                                window.location.href = "index.htm";
                            }
                        }
                    });
                } else {
                    window.location.href = "index.htm";
                }
            }
        });
    }
};

var WeixinBind = function (code, state) {
    //微信绑定
    this.weixinBind = function () {
        weixinBindHandle(code, state);
    }

    function weixinBindHandle(code, state) {
        //1，获取微信用户信息
        $.ajax({
            type: "post",
            url: "/member/user_weixin_info.htm",
            data: {"code": code},
            async: false,
            dataType: "json",
            success: function (result) {
                var res_msg = eval(result);
                if (res_msg.actionStatus == "success") {
                    var resData = eval("(" + res_msg.actionMessage + ")");
                    var postData = {
                        "openId": resData.openid,
                        "state": state,
                        "nickName": resData.nickname,
                        "unionId": resData.unionId
                    }
                    //2，进行微信绑定
                    $.ajax({
                        type: "post",
                        async: false,
                        url: "/member/bind_third.htm",
                        dataType: "json",
                        data: postData,
                        success: function (result) {
                            var data = eval(result);
                            if (data.actionStatus == 'success') {
                                //3，绑定微信成功跳转到绑定设置页面
                                window.location.href = "//member.banksteel.com/console/#/member/personal/security-setting?flag=1";
                            } else {
                                window.location.href = "//member.banksteel.com/console/#/member/personal/security-setting?flag=0&type=wx"; //回到 绑定设置页面 弹出失败弹窗
                            }
                        }
                    });
                } else {
                    window.location.href = "//member.banksteel.com/console/#/member/personal/security-setting?flag=0&type=wx"; //回到 绑定设置页面 弹出失败弹窗
                }
            }
        });
    }
}

String.prototype.replaceAll = function(s1,s2){ 
  return this.replace(new RegExp(s1,"gm"),s2); 
}